package cn.itcast.test;

import cn.itcast.n2.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

import static cn.itcast.n2.util.Sleeper.sleep;

/**
 * className: LockCas
 * description:
 * date: 2023/2/24-14:50
 * <p>
 * project: concurrent
 * package: cn.itcast.test
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Slf4j(topic = "c.LockCas")
public class LockCas {
    /**
     * 0 没加锁
     * 1 枷锁
     */
    private AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        while (true) {
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }

    public void unlock() {
        log.debug("unlock...");
        state.set(0);
    }

    public static void main(String[] args) {
        LockCas lock = new LockCas();
        new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try {
                log.debug("lock...");
                sleep(1);
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try {
                log.debug("lock...");
            } finally {
                lock.unlock();
            }
        }).start();
    }
}